import { ClassificationType, type Classification } from '@/models/Classification/Classification'
import { ref } from 'vue'
import type { useClassification } from './useClassification'
import { querySecondaryClassificationByParent } from '@/apis/Classification'
import { notification } from 'ant-design-vue'

export function useSecondaryClassification(
  useClassificationInstance: ReturnType<typeof useClassification>,
) {
  const secondaryClassificatList = ref<Classification[]>([])
  const loadingSecondaryClassificatList = ref(false)

  async function changeSecondaryClassificationList(code: string | undefined) {
    if (!code) {
      secondaryClassificatList.value = []
      return
    }
    const cacheResult = useClassificationInstance.secondaryClassificatListMapCache.value[code]
    if (cacheResult) {
      secondaryClassificatList.value = cacheResult
      return
    }
    if (loadingSecondaryClassificatList.value) return
    loadingSecondaryClassificatList.value = true
    try {
      const res = await querySecondaryClassificationByParent({
        code,
        type: ClassificationType.classification,
      })
      if (Array.isArray(res.data)) {
        secondaryClassificatList.value = res.data
        useClassificationInstance.addSecondaryClassificatListMapCache(code, res.data)
      } else {
        secondaryClassificatList.value = []
        notification.error({ message: `获取二级分类失败失败!` })
      }
    } catch (error) {
      secondaryClassificatList.value = []
      notification.error({ message: `获取二级分类失败失败!` })
    }
    loadingSecondaryClassificatList.value = false
  }

  return {
    secondaryClassificatList,
    loadingSecondaryClassificatList,
    changeSecondaryClassificationList,
  }
}
